<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="searchForm" status-icon ref="searchForm" action="javascript:void(0);" size="small">
        <el-row>
          <!--<el-col :xs="24" :sm='6'>
              <el-form-item label="菜单" label-width="40px" prop="filterText">
                  <el-input clearable placeholder="输入关键字进行过滤" v-model="searchForm.filterText"/>
              </el-form-item>
          </el-col>-->
          <el-col>
            <el-form-item>
              <el-button v-waves class="filter-item" type="success" icon="el-icon-plus"
                         @click="handleAdd()">新增
              </el-button>
              <!--<el-button v-waves type="warning"
                         icon="el-icon-refresh" @click="handleReset('searchForm')">重置
              </el-button>-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--搜索面板-->
    <div class="containtable">
      <el-table :data="tableData.item" v-loading="tableData.listLoading" border row-key="id"
                :expand-row-keys="tableData.rootKeys">
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column label="前端路由" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.path }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="菜单URL" width="200px"></el-table-column>
        <el-table-column label="类型" align="center" width="100px">
          <template slot-scope="scope">
            {{ typeMap[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="seq" label="排序" align="center" width="70px"></el-table-column>
        <el-table-column prop="icon" label="图标"></el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <el-button @click="add(scope.row)" type="success" size="mini" icon="el-icon-plus">添加</el-button>
            <el-button @click="edit(scope.row)" type="primary" size="mini" icon="el-icon-edit">编辑
            </el-button>
            <el-button @click="remove(scope.row)" type="danger" size="mini" icon="el-icon-remove">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--新增-->
    <el-dialog title="资源信息" :center="true" :visible.sync="editForm.show">
      <el-form :rules="rules" status-icon :model="editForm" ref="editForm"
               style="max-width: 880px;" label-width="80px">
        <el-row :gutter="100">
          <el-col :sm="24">
            <el-form-item label="名称" prop="name">
              <el-input type="text" v-model="editForm.name" placeholder="请输入资源名称"/>
            </el-form-item>
          </el-col>
          <el-col :sm="24">
            <el-form-item label="上级菜单" prop="selectOption">
              <el-cascader
                :options="editForm.options"
                v-model="editForm.selectOption"
                change-on-select style="width: 100%"
                :props="{label:'name', value:'id'}">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="资源类型" prop="res">
              <el-radio-group v-model="editForm.type">
                <el-radio v-for="item in types" :key="item.value" :label="item.value">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="排序" prop="seq">
              <el-input-number v-model="editForm.seq" :min="0" :max="999" label="描述文字"/>
            </el-form-item>
          </el-col>
          <el-col :sm="24">
            <el-form-item label="权限标识" prop="permission">
              <el-input type="text" v-model="editForm.permission" placeholder="权限标识"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="editForm.type === 'MENU'">
          <el-col :sm="24">
            <el-form-item label="url" prop="url">
              <el-input type="text" v-model="editForm.url" placeholder="请输入URL"/>
            </el-form-item>
          </el-col>
          <el-col :sm="24">
            <el-form-item label="路由" prop="path">
              <el-input type="text" v-model="editForm.path" placeholder="请输入路由链接"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="是否隐藏:" prop="isHidden">
              <el-switch v-model="editForm.isHidden" active-text="是" inactive-text="否"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="icon" prop="icon">
              <el-input type="text" v-model="editForm.icon" placeholder="请输入icon"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="editForm.isHidden">
          <el-col :sm="12">
            <el-form-item label="选中路径:" prop="redirect">
              <el-input type="text" v-model="editForm.redirect" placeholder="请输入子路由选中路径"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-waves @click="onSubmit('editForm')" icon="el-icon-success">提交</el-button>
      </div>
    </el-dialog>
    <!--新增-->
  </div>
</template>

<script>
import waves from '@/directive/waves' // Waves directive
import {
  checkPermission,
  edit,
  manageData,
  parentTree,
  resourceDel,
  resourceTree,
  typeMap,
  types
} from '@/api/admin/system/resource' //调用模块接口
export default {
  name: 'resourceManage',
  components: {},
  directives: {
    waves
  },
  data() {
    var checkPermission = (rule, value, callback) => {
      if (this.editForm.permission === '') {
        callback();
      }
      this.checkPer(rule, value, callback);
    };
    var checkRes = (rule, value, callback) => {
      if (this.editForm.type === '') {
        return callback(new Error('请选择类型'));
      } else {
        callback();
      }

    }
    return {
      types, typeMap,
      searchForm: {
        filterText: ''
      },
      tableData: {
        listLoading: false,
        item: [],
        rootKeys: []
      },
      editForm: {
        redirect: '',
        isHidden: false,
        show: false,
        id: '',
        name: '',
        seq: '',
        type: '',
        parentId: '',
        selectOption: ['0'],
        value: [],
        url: '',
        permission: '',//权限标识
        confirm_permission: '',
        path: '',
        icon: '',
        options: [],
      },
      rules: {
        name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }],
        permission: [{
          validator: checkPermission,
          trigger: 'blur'
        }],
        res: [{
          validator: checkRes,
          required: true,
          trigger: 'blur'
        }]
      },
      treeId: 0,
    }
  },
  watch: {
    'searchForm.filterText'(val) {
      this.$refs.tree2.filter(val);
    }
  },
  mounted() {
    this.tableData.listLoading = true;
    this.getResourceTree();
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleAdd() {
      this.getMenus();
      this.editForm.id = '';
      this.editForm.show = true;
      this.$nextTick(() => {
        this.$refs.editForm.resetFields();
      });
      this.editForm.type = 'MENU';
    },
    add(data) {
      this.editForm.id = '';
      this.editForm.show = true;
      this.getMenus().then(() => {
        this.$refs.editForm.resetFields();
        this.editForm.selectOption = [];

        if (data.parentId == 0) {
          this.editForm.selectOption.push(data.id);
        } else {
          this.editForm.selectOption = data.parentPath.replace(/^0,/, '').split(',');
          this.editForm.selectOption.push(data.id);
        }
        this.editForm.type = 'MENU';
      });
    },
    handleReset(formName) {
      this.$refs[formName].resetFields();
    },
    edit(data) {
      this.editForm.id = data.id;
      this.editForm.show = true;
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        this.$refs.editForm.resetFields();
      })
      Promise.all([
        this.getMenus(),
        manageData({
          id: data.id
        })
      ]).then(([, ress]) => {
        this.editForm.selectOption = ['0'];
        Object.entries(ress.data.resource).forEach(([key, val]) => {
          if (this.editForm[key] !== undefined) {
            this.editForm[key] = val;
          }
        });
        if (ress.data.resource.parentPath) {
          this.editForm.selectOption = [];
          this.editForm.selectOption = ress.data.resource.parentPath.replace(/^0,/, '').split(',');
        }
      })
    },
    remove(data) {
      this.$confirm('是否删除该资源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resourceDel({
          id: data.id
        }).then(res => {
          if (!res.success) {
            this.$message({
              type: 'error',
              message: '删除失败'
            });
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getResourceTree();
            this.editForm.show = false;
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //资源树
    getResourceTree() {
      resourceTree({}).then(res => {
        this.tableData.item = res.data.trees;
        this.tableData.rootKeys = res.data.trees.map(item => item.id);
        this.editForm.options = res.data.trees;
        this.tableData.listLoading = false;
      });
    },
    //上级菜单
    getMenus() {
      return new Promise(resolve => {
        parentTree({}).then(res => {
          this.editForm.options = res.data.parentTrees;
          resolve()
        });
      })
    },
    //校验权限标识
    checkPer(rule, value, callback) {
      if (this.editForm.id) {
        if (this.editForm.permission === this.editForm.confirm_permission) {
          callback();
        }
      }
      checkPermission({
        permission: this.editForm.permission,
        id: this.editForm.id
      }).then(res => {
        if (res.success) {
          if (res.data.exist) {
            return callback(new Error('当前标识已存在'));
          } else {
            callback();
          }
        }
      });
    },
    //提交
    onSubmit(editForm) {
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          if (this.editForm.selectOption.length > 0) {
            this.editForm.parentId = this.editForm.selectOption[this.editForm.selectOption.length - 1];
          }
          edit(this.editForm).then(res => {
            this.$notify({
              title: '提示',
              message: res.respMsg,
              type: 'success'
            });
            this.getResourceTree();
            this.editForm.show = false
          })
        } else {
          return false;
        }
      })
    }
  }
}
</script>

<style>

</style>
